package com.im.util;

import com.im.MDA;
import com.im.service.dto.BaseException;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.Collection;
import java.util.Map;

/**
 * 协议处理工具类
 * 
 * @author 
 * 
 */
public class ReturnsUtil {

	/**
	 * 处理成功返回协议对象
	 * @param jsonObject 
	 * @return
	 */
	public static JSONObject returnSuccess(Object jsonObject, boolean isFilteNull){
		JSONObject jsonObj = new JSONObject();
		jsonObj.put("resultCode",MDA.RESULT_SUCCESS);
		jsonObj.put("resultMsg","处理成功!");
		//System.out.println(JSONObject.fromObject(jsonObject));
		
		if(jsonObject instanceof Collection || jsonObject.getClass().isArray()){
			jsonObj.put("result", JSONArray.fromObject(jsonObject,isFilteNull?JsonUtil.FILTENULL_AND_DATTE_JSONCONF:JsonUtil.DEFAULT_AND_DATTE_JSONCONF));
		}else{
			jsonObj.put("result",JSONObject.fromObject(jsonObject,isFilteNull?JsonUtil.FILTENULL_AND_DATTE_JSONCONF:JsonUtil.DEFAULT_AND_DATTE_JSONCONF));
		}
		return jsonObj;
	}

	/**
	 * 处理成功返回协议对象
	 * @param jsonObject 
	 * @return
	 */
	public static JSONObject returnSuccess(Object jsonObject){
		return returnSuccess(jsonObject, false);
	}

	
	/**
	 * 生成错误堆栈信息
	 * @param e
	 * @return
	 */
	public static String getStackTrackMessage(Exception e) {
        StringBuffer messsage = new StringBuffer();
        if (e != null) {
        	messsage.append(e.getClass()).append(": ").append(e.getMessage()).append("\n");
            StackTraceElement[] elements = e.getStackTrace();
            for (StackTraceElement stackTraceElement : elements) {
                messsage.append("\t").append(stackTraceElement.toString()).append("\n");
            }
            Throwable localThrowable = e.getCause();
            if (localThrowable != null) {
            	getStackTraceAsCause(messsage, localThrowable);
            }
        }
        return messsage.toString();
    }

	private static void getStackTraceAsCause(StringBuffer messsage, Throwable localThrowable) {
		messsage.append(localThrowable.getClass()).append(": ").append(localThrowable.getMessage()).append("\n");
        StackTraceElement[] elements = localThrowable.getStackTrace();
        for (StackTraceElement stackTraceElement : elements) {
            messsage.append("\t").append(stackTraceElement.toString()).append("\n");
        }
		localThrowable = localThrowable.getCause();
		if (localThrowable != null) {
        	getStackTraceAsCause(messsage, localThrowable);
        }
	}
	
	public static String returnFailure(String message){
		JSONObject jsonObj = new JSONObject();
		jsonObj.put("resultCode",MDA.RESULT_FAIL);
		jsonObj.put("resultMsg","失败!");
		JSONObject resultMsgjsonObj = new JSONObject();
		resultMsgjsonObj.put("message",message);
		jsonObj.put("result", resultMsgjsonObj);
		return jsonObj.toString();
	}
	
	
	/**
	 * 处理异常
	 * @param msg 异常信息
	 * @return
	 */
	public static JSONObject returnException(String code ,String msg, Exception e){
		JSONObject jsonObj = new JSONObject();
		jsonObj.put("resultCode",MDA.RESULT_FAIL);
		if(msg!=null){
			jsonObj.put("resultMsg",msg);
		}
		if(code!=null){
			jsonObj.put("errCode", code);
		}
		if(e!=null){
			if(e instanceof BaseException){
				String errorStr = ((BaseException) e).getError();
				Integer errorCode = ((BaseException) e).getCode();
				if(errorCode!=null){
					jsonObj.put("errCode", errorCode);
				}
				if(StringUtil.isNotBlank(errorStr)&&!"RuntimeException".equals(errorStr)){
					jsonObj.put("errCode", errorStr);
				}
			}
			jsonObj.put("errorStack", getStackTrackMessage(e));
		}
		if(!jsonObj.containsKey("errCode")){
			//如果业务代码中没有异常编码，即使用受理的通用异常编码
			jsonObj.put("errCode","020064");
		}
		String errCode = JsonUtil.getStringFromJSON(jsonObj, "errCode", "异常出参");
		if(StringUtil.isNotBlank(errCode)&&"-2".equals(errCode)){
			jsonObj.element("resultCode", errCode);
			jsonObj.element("resultMsg", msg);
			jsonObj.element("errCode", "029999");
		}
		return jsonObj;
	}
	/**
	 * 处理异常
	 * @param msg 异常信息
	 * @return
	 */
	public static JSONObject returnException(String msg,Exception e){
		return returnException(null,msg,e);
		/*JSONObject jsonObj = new JSONObject();
		jsonObj.put("resultCode","-1");
		jsonObj.put("resultMsg",msg);
		if(e!=null){
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			e.printStackTrace(new PrintStream(out));
			jsonObj.put("errorStack", new String(out.toByteArray()));
		}
		return jsonObj;*/
	}

	/**
	 * 构建返回错误提示map
	 * @param resultMap
	 * @param errorMsg
	 * @return
	 */
	public static Map<String,Object> buildFailMap(Map<String,Object> resultMap,String errorMsg){
		resultMap.put("resultCode","-1");
		resultMap.put("resultMsg",errorMsg);
		return resultMap;
	}
	
//	/**
//	 * 异常编码组装
//	 * @param msg 
//	 * @return
//	 */
//	public static String errCode(long errTypeCode,long errSourceCode,long errSeq){
//		if(StringUtil.isObjectEmpty(errTypeCode)){
//			errTypeCode = 00L;
//		}
//		if(StringUtil.isObjectEmpty(errSourceCode)){
//			errSourceCode = 00L;
//		}
//		if(StringUtil.isObjectEmpty(errSeq)){
//			errSeq = 00L;
//		}
//		return  String.valueOf(errTypeCode) + String.valueOf(errSourceCode) + com.icar.common.MDA.ERR_CODE_PREINDEX +String.valueOf(errSeq);
//	}
}
